package com.help.common.interceptors;


import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.help.common.api.CommonResult;
import com.help.common.api.ResultCode;
import com.help.common.util.JsonUtil;
import com.help.common.util.JwtUtil;
import com.help.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 用户操作拦截器
 * @author 风亦未止
 * @date 2021/9/20 22:44
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = null;
        String errorToken = JsonUtil.toJSON(CommonResult.failed(ResultCode.UNAUTHORIZED));
//        log.info("拦截器走起~");
        String token = request.getHeader("token");
        DecodedJWT decode =null;
        try {
           decode = JwtUtil.verify(token);
        } catch (Exception e) {
            writer=response.getWriter();
            writer.print(errorToken);
            writer.close();
//            log.info("未登录~");
            return false;
        }
        Map<String,Object> user = decode.getClaim("user").asMap();
        String openid = (String) user.get("openid");
        log.info("用户openid："+openid+"已登录！");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
